package com.ruixin.servlet;

import com.ruixin.base.exception.BaseException;
import com.ruixin.mvc.config.ApplicationContextWrapper;
import com.ruixin.mvc.config.RequestHandlerAdaptor;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 入口
 */
public class DispatcherServlet extends HttpServlet {

    protected ApplicationContextWrapper context;

    public DispatcherServlet(){}

    public DispatcherServlet(ApplicationContextWrapper context){
        this.context = context;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doDelete(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doDelete(req, resp);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doDelete(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            RequestHandlerAdaptor handlerAdaptor = new RequestHandlerAdaptor(this.context);
            handlerAdaptor.hander(req, resp);
        }catch (BaseException e){
            resp.sendError(500,e.getMessage());
        }
    }
}
